const { Service } = require("egg");
const fs = require('fs');


class UserService extends Service {
  async create(data) {
    const { ctx } = this;
    return await ctx.model.Article.create(data).then((res) => {
      return res ? res.toJSON() : res;
    });;
  }

  async getArticle(where) {
    const { ctx } = this;
    return await ctx.model.Article.findOne({ where: where }).then((res) => {
      return res ? res.toJSON() : res;
    });
  }
  async searchQuery(search, ids) {
    const { ctx } = this;
    const searchTerm = `%${search}%`;
    const where = {
      title: { [ctx.app.Sequelize.Op.like]: searchTerm },
      id: {
        [this.app.Sequelize.Op.in]: ids,
      },
    };
    const res = await ctx.model.Article.findAll({
      raw: true,
      order: [["publishTime", "DESC"]],
      attributes: { exclude: ["detail"] },
      where,
    });
    return res;
  }

  async list(query) {
    const { pageNum = 1, pageSize = 20 } = query; // 默认值设置
    const offset = (pageNum - 1) * pageSize;
    const { ctx } = this;
    const datas = await ctx.model.Article.findAll({
      raw: true,
      order: [["publishTime", "DESC"]],
      attributes: { exclude: ["detail"] },
      limit: pageSize,
      offset: offset,
    });
    const total = await ctx.model.Article.count();
    const hasNextPage = offset + pageSize < total;
    return {
      total,
      pageNum,
      pageSize,
      hasNextPage,
      sorts: datas,
    
    };
  }

  async update(where, updates) {
    const { ctx } = this;
    return await ctx.model.Article.update(updates, {
      where,
    });
  }

  async findOne(where) {
    const { app } = this;
    const existingDirectory = await app.model.Article.findOne({
      where,
    });
    return existingDirectory;
  }

  async findByIds(ids) {
    const { app } = this;

    const allArticles = await app.model.Article.findAll({
      raw: true,
      where: {
        id: {
          [app.Sequelize.Op.in]: ids,
        },
      },
    });

    let articlesMap = {};

    allArticles.forEach((article) => {
      articlesMap[article.id] = article;
    });

    const sortedArticles = ids
      .map((id) => articlesMap[id])
      .filter((article) => article !== undefined);

    return sortedArticles;
  }

  async importContent(url) {
    const { service } = this;
    const result = await service.crawler.saveDivContent(url);
    const { classify } = result;
    if (classify) {
        await service.articleClassify.create(classify);
    }
    const res = await service.article.create(result);
    return {
      id: res.id,
      ...result,
    };
  }
}

module.exports = UserService;
